'use strict';

var extend = require('util')._extend;

var through = require('through2');
var defaultJade = require('pug');
var ext = require('gulp-util').replaceExtension;
var PluginError = require('gulp-util').PluginError;
//var wrap = require('jade-runtime/wrap');

var path=require('path');

module.exports = function(options){
    var opts = extend({}, options);
    var jade = opts.jade || defaultJade;

    function CompileJade(file, enc, cb){
        opts.filename = file.path;
        opts.name=path.basename(file.path, path.extname(file.path)).replace("template_","");
        opts.compileDebug=false;
        //while(true)1+1;

        if(file.data){
            opts.data = file.data;
        }

        file.path = ext(file.path, ".js");

        if(file.isStream()){
            return cb(new PluginError('gulp-jade', 'Streaming not supported'));
        }

        if(file.isBuffer()){
            try {
                var compiled;
                var contents = String(file.contents);
                compiled = jade.compileClient(contents, opts);
                file.contents = new Buffer(compiled);
            } catch(e) {
                return cb(new PluginError('gulp-jade', e));
            }
        }
        cb(null, file);
    }

    return through.obj(CompileJade);
};
